package creational.prototype;

/**
 * @ClassName: MainTest01
 * @Description: 测试：深拷贝
 * @Author: liu-hao
 * @Date: 2023-05-19 23:18
 * @Version: 1.0
 **/
public class MainTest02 {
    public static void main(String[] args) throws Exception {
        Person2 p1 = new Person2();
        Person2 p2 = (Person2) p1.clone();
        System.out.println("p1==p2: " + (p1 == p2)); // false
        System.out.println("p1.loc==p2.loc: " + (p1.loc == p2.loc)); // false

        p1.loc.street = "上海";
        System.out.println("p1.loc:   " + p1.loc); // 上海
        System.out.println("p2.loc:   " + p2.loc); // 北京
    }
}

// 具体原型角色
class Person2 implements Cloneable {
    int age = 8;
    int score = 100;
    Location2 loc = new Location2("北京", 22); // 引用型对象

    @Override
    public Object clone() throws CloneNotSupportedException {
        Person2 p = (Person2) super.clone();
        p.loc = (Location2) loc.clone();
        return p;
    }
}

// 原型中依赖的类
class Location2 implements Cloneable {
    String street;
    int roomNo;

    public Location2(String street, int roomNo) {
        this.street = street;
        this.roomNo = roomNo;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Location{" +
                "street='" + street + '\'' +
                ", roomNo=" + roomNo +
                '}';
    }

}